package it.fuesi.synotools.helpers;

import android.content.Context;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import it.fuesi.synotools.R;

/**
 * Created by pascotto on 28/10/14.
 */
public class FormatHelper {

    public static String formatBreadCrumb(String path){
        if(path == null) return null;

        return path.replaceAll("[/]", " > ");
    }

    public static String formatPercent(double n){
        String x = ""+n;
        String[] s = x.split("[.]");
        if(s.length > 0)
            x = s[0];
        if(s.length > 1){
            String dec = s[1];
            if(dec.length() > 2)
                dec = dec.substring(0,1);

            x += "." + dec;
        }

        return x + "%";
    }


    public static String formatFileSize(long size){
        long[] divider = {1000000000000l, 1000000000l, 1000000l, 1000l, 1l};
        String[] suffix = {"Tb","Gb", "Mb", "Kb", "Bytes"};
        int i=0;
        long n = 0;
        while(n<=0 && i<divider.length){
            n = size / divider[i];
            i++;
        }
        i--;
        String rest = ""+ (size % divider[i]);
        if(rest.length() > 2)
            rest = rest.substring(0,1);
        return n + "." + rest + " " + suffix[i];
    }

    public static String formatSpeed(long speed){
        long[] divider = {1000000000, 1000000, 1000, 1};
        String[] suffix = {"Gb/s", "Mb/s", "Kb/s", "b/s"};
        int i=0;
        long n = 0;
        while(n<=0 && i<divider.length){
            n = speed / divider[i];
            i++;
        }
        i--;
        return n + " " + suffix[i];
    }

    public static String urlEncode(String unencoded){
        try {
            if(unencoded == null || unencoded.isEmpty()) return unencoded;
            String encoded = URLEncoder.encode(unencoded, "UTF-8").replaceAll("[+]", "%20");
            String finalString = "";
            for(int i=0; i<encoded.length(); i++){
                char c = encoded.charAt(i);
                if(c == '%' && encoded.charAt(i+1) == '2' && encoded.charAt(i+2) =='C')
                    finalString += "%5C";

                finalString += c;
            }
            return finalString;
        } catch (UnsupportedEncodingException e) {
            return unencoded;
        }
    }

    public static String formatTimeMillis(Context ctx, long time){
        return formatTime(ctx, time / 1000);
    }

    public static String formatTime(Context ctx, long time){
        long[] divider = {86400, 3600, 60, 1};
        String[] suffix = ctx.getResources().getStringArray(R.array.time_measure_units);
        int i=0;
        long n = 0;
        while(n<=0 && i<divider.length){
            n = time / divider[i];
            i++;
        }
        i--;
        return n + " " + suffix[i];
    }

}
